const db = wx.cloud.database();

Page({
  data: {
    currentTopic: 'southern', 
    sections: [
      { id: 'origin', name: '起源' },
      { id: 'development', name: '发展' },
      { id: 'history', name: '历史' },
      { id: 'significance', name: '意义' }
    ],
    messages:[],
    currentSection: 'origin',  
    scrollTop: 0 
  },

  // 切换主题
  switchTopic(event) {
    const topic = event.currentTarget.dataset.topic;
    this.setData({
      currentTopic: topic,
      currentSection: 'origin', 
      scrollTop: 0 
    });
  },

  // 点击左侧导航栏，滚动到对应部分

  scrollToSection(event) {
    const sectionId = event.currentTarget.dataset.id;
    const query = wx.createSelectorQuery().in(this);

    // 获取对应section的位置信息
    query.select(`#${sectionId}`).boundingClientRect((rect) => {
      // 设置scrollTop值和currentSection
      this.setData({
        currentSection: sectionId,
        scrollTop: rect.top + this.data.scrollTop // 设置scrollTop值
      });
    }).exec();
  },

  onScroll(event) {
    const scrollTop = event.detail.scrollTop;
    const query = wx.createSelectorQuery().in(this);

    query.selectAll('.section').boundingClientRect((rects) => {
      rects.forEach((rect) => {
        if (scrollTop >= rect.top - 50 && scrollTop < rect.bottom) {
          // 只在滚动时更新currentSection
          this.setData({
            currentSection: rect.id
          });
        }
      });
    }).exec();
  },

  onLoad: function(){
    db.collection('different').get().then(res =>{
      this.setData({
        messages:res.data
      })
    })
  }
});
